package com.myapp.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myapp.api.entity.Major;
import com.myapp.api.service.DeptService;
import com.myapp.api.service.MajorService;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.ResultStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Api(value = "MajorController",description = "major 表的相关 CURD 操作")
@RestController
@RequestMapping(value = "/major", produces = "application/json;charset=UTF-8")
public class MajorController {
    @Autowired
    private MajorService service1;
    @Autowired
    private DeptService service2;

    @ApiOperation(value="获取专业信息列表",notes="获取所有的专业信息",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/all")
    public ResponseEntity<?> getMajors(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        String orderBy = "CreateTime DESC";
        PageHelper.startPage(pageNum, pageSize, orderBy);
        List<Major> major = service1.getMajors();

        HttpStatus status = HttpStatus.OK;
        PageInfo<Major> records = new PageInfo<>(major);
        return new ResponseEntity<PageInfo<Major>>(records, status);
    }

    @ApiOperation(value="获取专业详细信息",notes="根据 url 的专业编号来获取详细信息",produces = "application/json")
    @ApiImplicitParam(name = "mid", value = "专业编号", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/{mid}")
    public ResponseEntity<?> getMajorByMid(@PathVariable(value = "mid") String mid) {
        if (!mid.equals(0)) {
            Major record = service1.getMajorbyMid(mid);

            HttpStatus status = HttpStatus.OK;
            Object obj = new Object();
            if (record == null)
                return new ResponseEntity<Object>(obj, status);
            else
                return new ResponseEntity<Major>(record, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="根据专业名查询课程信息",notes="通过模糊匹配专业名",produces = "application/json")
//    @ApiImplicitParams({
    @ApiImplicitParam(name = "cname", value = "专业名关键词", required = true, dataType = "String", paramType = "query")
//            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
//            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
//    })
//  @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize
    @GetMapping
    public ResponseEntity<?> getMajorByMname(@RequestParam(value = "mname") String mname) {
        if (!mname.equals("") && !mname.isEmpty()) {
            List<Major> major = null;
            try {
//                String orderBy = "CreateTime DESC";
//                PageHelper.startPage(pageNum, pageSize, orderBy);
                major = service1.getMajorByMname(URLDecoder.decode(mname, "utf-8"));
//                record = new PageInfo<>(major);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<List<Major>>(major, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "专业名称不能为空 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="新增专业信息",notes="新增专业信息,专业编号不允许重复,不允许提交不存在的院系编号",produces = "application/json")
    @PostMapping
    public ResponseEntity<?> addMajor(@Valid @RequestBody Major record, BindingResult bindingResult) {
        record.setCreatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service1.getMajorbyOneMid(record.getMid());
            Integer findDid = service2.getDeptByOneDid(record.getDid());

            if (!findOne.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的专业编号" + record.getMid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else if (findDid.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的院系编号" + record.getDid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service1.addMajor(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                    JsonResult jsonResult = new JsonResult(ResultStatus.ADD_DATA_ERROR, "Add Major Data is Error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }

    @ApiOperation(value="删除专业",notes="根据 url 的 id 来删除专业",produces = "application/json")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delMajorById(@PathVariable(value = "id") Integer id) {
        if (!id.equals(0)) {
            int result = service1.deleteMajorById(id);
            if (result > 0) {
                HttpStatus status = HttpStatus.OK;
                JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                return new ResponseEntity<JsonResult>(jsonResult, status);
            } else {
                HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                JsonResult jsonResult = new JsonResult(ResultStatus.DELETE_DATA_ERROR, "Delete Major Data is Error, the id is" + id + " !!!");
                return new ResponseEntity<JsonResult>(jsonResult, status);
            }
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(result, status);
        }
    }

    @ApiOperation(value="修改专业信息",notes="修改专业信息,院系编号不允许重复",produces = "application/json")
    @PutMapping
    public ResponseEntity<?> putMajor(@Valid @RequestBody Major record, BindingResult bindingResult) {
        record.setUpdatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service1.getMajorbyOneMid(record.getMid());
            Integer findDid = service2.getDeptByOneDid(record.getDid());

            if (!findOne.equals(1)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的专业编号" + record.getMid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else if (findDid.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的院系编号" + record.getDid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service1.putMajor(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult jsonResult = new JsonResult(ResultStatus.UPDATE_DATA_ERROR, "Update Major is error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }
}
